package alo.p4.work;

import org.junit.Test;

import java.util.Stack;
//计算后缀表达式的值
public class InToPost1 {

    @Test
    public void test(){
        Solution1 solution1=new Solution1();
        int s= solution1.complete("123*+5-");
        System.out.println(s);//2

    }

    class Solution1 {
        public  int complete(String str){
            //把字符串转换为字符数组
            char arr[] = str.toCharArray();
            int num1 = 0;
            int num2 = 0;
            //只有数字进入栈
            Stack<Integer> stack = new Stack<Integer>();
            for (int i=0;i<arr.length;i++){
                if (arr[i] == '+'){
                    num1 = stack.pop();
                    num2 = stack.pop();
                    stack.push(num2+num1);
                }else if (arr[i] == '-'){
                    num1 = stack.pop();
                    num2 = stack.pop();
                    stack.push(num2-num1);
                }else if (arr[i] == '*'){
                    num1 = stack.pop();
                    num2 = stack.pop();
                    stack.push(num2*num1);
                }else if (arr[i] == '/'){
                    num1 = stack.pop();
                    num2 = stack.pop();
                    stack.push(num2/num1);
                }else{
                    //把字符数字转换为数组，压栈
                    stack.push(arr[i]-48);
                }
            }
            return stack.pop();
        }
    }
}
